package org.dromara.comm_lhz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.comm_lhz.entity.AsSearchHistoryEntity;
import org.dromara.comm_lhz.mapper.AsSearchHistoryMapper;
import org.dromara.comm_lhz.service.AsSearchHistoryService;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.LinkedHashMap;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 搜索历史服务实现类
 */
@Service
public class AsSearchHistoryServiceImpl extends ServiceImpl<AsSearchHistoryMapper, AsSearchHistoryEntity> implements AsSearchHistoryService {

    @Autowired
    private AsSearchHistoryMapper asSearchHistoryMapper;

    /**
     * 查询当前用户的搜索历史
     *
     * @return 搜索历史列表
     */
    @Override
    public List<AsSearchHistoryEntity> selSearchHistory() {
        Long userId = LoginHelper.getUserId(); // 获取当前用户ID

        LambdaQueryWrapper<AsSearchHistoryEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AsSearchHistoryEntity::getUserId, userId); // 根据用户ID查询

        List<AsSearchHistoryEntity> searchHistoryList = asSearchHistoryMapper.selectList(queryWrapper);

        // 使用Java Stream API根据searchHistory字段去重
        List<AsSearchHistoryEntity> uniqueSearchHistoryList = searchHistoryList.stream()
            .collect(Collectors.collectingAndThen(
                Collectors.toMap(
                    AsSearchHistoryEntity::getSearchHistory, // 使用searchHistory作为key
                    Function.identity(), // 使用实体本身作为值
                    (existing, replacement) -> existing, // 如果有重复，保留第一个遇到的记录
                    LinkedHashMap::new // 保持插入顺序
                ),
                map -> new ArrayList<>(map.values()) // 转换为列表
            ));

        return uniqueSearchHistoryList;
    }

    /**
     * 添加搜索历史
     *
     * @param asSearchHistoryEntity 搜索历史实体
     */
    @Override
    public void addSearchHistory(AsSearchHistoryEntity asSearchHistoryEntity) {
        Long userId = LoginHelper.getUserId(); // 获取当前用户ID
        asSearchHistoryEntity.setUserId(userId);
        asSearchHistoryMapper.insert(asSearchHistoryEntity);
    }
    /**
     * 删除搜索历史
     */
    @Override
    public void deleteSearchHistory() {
        Long userId = LoginHelper.getUserId(); // 获取当前用户ID

        // 创建LambdaQueryWrapper用于指定删除条件
        LambdaQueryWrapper<AsSearchHistoryEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AsSearchHistoryEntity::getUserId, userId);

        // 调用remove方法删除符合条件的记录
        asSearchHistoryMapper.delete(queryWrapper);
    }

}
